package com.codegeek.project.system.controller;

import com.codegeek.common.constant.UserConstants;
import com.codegeek.common.utils.SecurityUtils;
import com.codegeek.common.utils.ServletUtils;
import com.codegeek.common.utils.StringUtils;
import com.codegeek.common.utils.poi.ExcelUtil;
import com.codegeek.framework.aspectj.lang.annotation.Log;
import com.codegeek.framework.aspectj.lang.enums.BusinessType;
import com.codegeek.framework.security.LoginUser;
import com.codegeek.framework.security.service.TokenService;
import com.codegeek.framework.web.controller.BaseController;
import com.codegeek.framework.web.domain.AjaxResult;
import com.codegeek.framework.web.page.TableDataInfo;
import com.codegeek.project.common.Decode;
import com.codegeek.project.system.domain.SysRole;
import com.codegeek.project.system.domain.SysUser;
import com.codegeek.project.system.service.ISysPostService;
import com.codegeek.project.system.service.ISysRoleService;
import com.codegeek.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 用户信息
 *
 * @author codegeek
 */
@RestController
@RequestMapping("/system/user")
@Api(value = "用户管理Controller", tags = {"用户管理操作接口"})
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取用户列表
     */
    @ApiOperation("查询用户管理table列表")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @ApiOperation("导出用户管理数据")
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @ApiOperation("导入用户管理数据")
    @PostMapping("/importData")
    @PreAuthorize("@ss.hasPermi('system:user:importData')")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    @ApiOperation("导入用户管理模板")
    @PreAuthorize("@ss.hasPermi('system:user:importTemplate')")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取用户管理详细信息")
    @GetMapping(value = {"/", "/{userId}"})
    @PreAuthorize("@ss.hasPermi('system:user:getInfo')")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("roles", roleService.selectRoleList(new SysRole()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户管理用户")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    public AjaxResult add(@Validated @RequestBody SysUser user, @RequestParam("newsValue") String newsValue) throws Exception {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setPassword(Decode.getValue(user.getPassword().replace("$","+")));
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.updataSlopUserHaveUserIncrease(newsValue);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户管理用户")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/updateUser")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    public AjaxResult updateUser(@Validated @RequestBody SysUser user, @RequestParam("newsValue") String newsValue, @RequestParam("oldValue") String oldValue) throws Exception {
        try {
            userService.checkUserAllowed(user);
            if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
                return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
            } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
                return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
            user.setUpdateBy(SecurityUtils.getUsername());
            if (!newsValue.equals(oldValue)) {
                userService.updataSlopUserHaveUserIncrease(newsValue);
                userService.updataSlopUserHaveUserReduce(oldValue);
            }
            userService.updateUser(user);
            return AjaxResult.success("修改成功");
        } catch (Exception e) {
            return AjaxResult.error();
        }
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户管理用户")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/{userIds}")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        try {
            for (Long id :userIds) {
                SysUser sysUser = userService.selectUserById(id);
                userService.updataSlopUserHaveUserReduce(sysUser.getRoles().get(0).getRoleName());
            }
        } catch (Exception e) {}
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置用户管理密码")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    public AjaxResult resetPwd(@RequestBody SysUser user,
                               @RequestParam("loginPassword") String loginP,
                               @RequestParam("newPassword") String newP,
                               @RequestParam("checkPassword") String checkP) throws Exception {
        loginP = loginP.replace("$","+");
        newP = newP.replace("$","+");
        checkP = checkP.replace("$","+");
        String loginPassword = Decode.getValue(loginP);
        String newPassword = Decode.getValue(newP);
        String checkPassword = Decode.getValue(checkP);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String loginPwd = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(loginPassword, loginPwd)) {
            return AjaxResult.error("当前登陆用户密码输入错误");
        }
        if (!newPassword.equals(checkPassword)) {
            return AjaxResult.error("两次密码不一致");
        }
        if (SecurityUtils.matchesPassword(newPassword, checkPassword)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(newPassword));
        user.setUpdateBy(loginUser.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation("修改用户管理状态")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @PreAuthorize("@ss.hasPermi('system:user:changeStatus')")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        System.out.println("修改用户管理状态");
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }


    /**
     * 批量禁用
     */
    @ApiOperation("批量禁用")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/selectedDisable")
    @PreAuthorize("@ss.hasPermi('system:user:selectedDisable')")
    public AjaxResult selectedDisable(@RequestBody List<Long> ids) {
        if (ids == null) {
            return null;
        }
        return toAjax(userService.selectedDisable(ids));
    }
}
